package com.drd.dt.util;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class ClientAuthorizationUtil {

	public static String hmacSHA1(String key, String uri, Map<String, String> headersMap, String body)
			throws UnsupportedEncodingException {
		if (uri == null) {
			throw new NullPointerException("uri is null");
		}
		StringBuilder sb = new StringBuilder("");
		sb.append(uri);
		sb.append("\n");
		if (headersMap != null && headersMap.size() > 0) {
			TreeMap<String, String> sortedHeadersMap = new TreeMap<>();
			for (Entry<String, String> entry : headersMap.entrySet()) {
				sortedHeadersMap.put(entry.getKey().toLowerCase(), entry.getValue());
			}
			for (Entry<String, String> entry : sortedHeadersMap.entrySet()) {
				sb.append(entry.getKey()).append(":").append(entry.getValue().replace(" ", "")).append("\n");
			}
		}
		System.out.println("加密前:" + sb);
		SecurityUtil.MacHashFunction hashFunction = SecurityUtil.hmacSha1(key)
				.hash(sb.toString().getBytes(SecurityUtil.UTF8));
		// System.out.println("第一次加密:"+hashFunction.result());
		if (body != null) {
			hashFunction.hash(body.getBytes(SecurityUtil.UTF8));
			// System.out.println("第二次加密:"+hashFunction.result());
		}
		// hashFunction.hash(sb.toString().getBytes(SecurityUtil.UTF8));
		// System.out.println("第三次加密:"+hashFunction.result());
		return hashFunction.result();
	}

	public static String hmacSHA1Mod2(String key, String uri, Map<String, String> headersMap, String body)
			throws UnsupportedEncodingException {
		if (uri == null) {
			throw new NullPointerException("uri is null");
		}
		long reqTimestamp = Long.valueOf(headersMap.get("x-beisheng-auth-timestamp"));
		long currTimestamp = System.currentTimeMillis();
		if (Math.abs(currTimestamp - reqTimestamp) > 60 * 5 * 1000) {
			throw new NullPointerException("时间间隔超过10秒");
		}
		StringBuilder sb = new StringBuilder("");
		sb.append(uri);
		sb.append("\n");
		if (headersMap != null && headersMap.size() > 0) {
			TreeMap<String, String> sortedHeadersMap = new TreeMap<>();
			for (Entry<String, String> entry : headersMap.entrySet()) {
				sortedHeadersMap.put(entry.getKey().toLowerCase(), entry.getValue());
			}
			for (Entry<String, String> entry : sortedHeadersMap.entrySet()) {
				sb.append(entry.getKey()).append(":").append(entry.getValue().replace(" ", "")).append("\n");
			}
		}
		// System.out.println("加密前:\n"+sb+(body!=null? body: ""));
		SecurityUtil.MacHashFunction hashFunction = null;
		if (body != null) {
			hashFunction = SecurityUtil.hmacSha1(key).hash((sb.toString() + body).getBytes(SecurityUtil.UTF8));
		} else {
			hashFunction = SecurityUtil.hmacSha1(key).hash((sb.toString()).getBytes(SecurityUtil.UTF8));
		}
		return hashFunction.result();
	}
}
